﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Net.NetworkInformation;
using System.Runtime.Serialization;
using RssReaderTemplate.Model;
using Microsoft.Phone.Reactive;

namespace RssReaderTemplate.ViewModels
{
    [DataContract]
    public class NetworkRequiredViewModel : ViewModelBase, IDisposable
    {
        public NetworkRequiredViewModel()
        {
            IsNetworkAvailable = NetworkInterface.GetIsNetworkAvailable();
            _networkMonitor = new NetworkMonitor();
            _networkMonitor.Subscribe(x => IsNetworkAvailable = x);
        }

        ~NetworkRequiredViewModel()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
            }
        }

        private NetworkMonitor _networkMonitor;

        public NetworkMonitor NetworkMonitor
        {
            get { return _networkMonitor; }
            set { _networkMonitor = value;
            OnPropertyChanged("NetworkMonitor");
            }
        }


        private bool _isNetworkAvailable;

        [DataMember]
        public bool IsNetworkAvailable
        {
            get
            {
                return _isNetworkAvailable;
            }
            set
            {
                if (value ^ _isNetworkAvailable)
                {
                    _isNetworkAvailable = value;
                    OnPropertyChanged("IsNetworkAvailable");
                }
            }
        }

        public IDisposable Subscribe(IObserver<bool> observer)
        {
            return _networkMonitor.Subscribe(observer);
        }
    }
}
